<template>
  <TablePage>
    <template #top>
      <SearchForm title="菜单管理">
        <template #extraButtons>
          <a-button type="primary" @click="showCreateModal">新增根菜单</a-button>
        </template>
      </SearchForm>
    </template>
    <SlTable
      :columns="columns"
      row-key="menuId"
      :data-source="tableData"
      :pagination="pagination"
      :loading="tableLoading"
    >
      <template #bodyCell="{ column, record }">
        <div v-if="column.key === 'oper'">
          <div>
            <a @click="showUpdateModal(record)">编辑</a>
            <a class="ml-2 text-red-400" @click="handleDelete(record)">删除</a>
          </div>
          <div v-if="record.menuType === MenuType.FEATURE || record.menuType === MenuType.FUNCTION">
            <a @click="addSubMenu(record)">新增子菜单</a>
          </div>
        </div>
      </template>
    </SlTable>
    <CURDDialog
      ref="CURDModalIns"
      id-key="menuId"
      :columns="columns"
      create-title="新增菜单"
      update-title="编辑菜单"
      delete-message="确认删除该菜单吗？"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :model-rules="modelRules"
      :table-data="tableData"
      :oper-data="operData"
      :curd="curd"
      :reload-table="reloadTable"
      :delete-url-suffix-mode="2"
      @before-ok="beforeOk"
      @open="open"
    />
  </TablePage>
</template>
<script lang="ts" setup>
import { onMounted, ref, shallowRef } from "vue";
import { useI18n } from "/@/locales/useI18n";
import { useCURD } from "/@/hooks/useCURD";
import { FormItemComponentType, CURDAction, CURDDialogExpose } from "/@/components/CURDDialog/models";
import type { FormItemData, OperItem, ShowCURDModalOptions, CURDModalEvent } from "/@/components/CURDDialog/models";
import type { TableProps } from "ant-design-vue";
import { PatternKey } from "/@/utils/verify";
import { Api } from "/@/api/home/menu";
import { MenuItem, MenuType } from "/@/api/home/menu/models";
import { handleMenuSort } from "/@/stores/menu";

const { t } = useI18n();
const columns = ref<TableProps<Partial<MenuItem>>["columns"]>([
  {
    title: "名称",
    dataIndex: "menuName",
  },
  {
    title: "图标",
    dataIndex: "icon",
  },
  {
    title: "动作",
    dataIndex: "path",
  },
  {
    title: "类型",
    dataIndex: "menuType",
    customRender({ text }) {
      return t(`baseData.menuType.${text}`);
    },
  },
  {
    title: "排序",
    dataIndex: "orderNum",
  },
  {
    title: t("common.oper"),
    key: "oper",
    width: 100,
  },
]);
const model = ref<Partial<MenuItem>>({
  menuName: "",
  icon: "",
  path: "",
  menuType: MenuType.FUNCTION,
  orderNum: 999,
});
const modelRules = ["menuName", "path", "menuType", "orderNum"];
function getMenuTypeData(superMenuItem?: MenuItem) {
  let data = [
    { label: "目录", value: MenuType.FEATURE },
    { label: "页面", value: MenuType.FUNCTION },
    { label: "按钮", value: MenuType.OPERATION },
  ];
  if (superMenuItem) {
    if (superMenuItem.menuType === MenuType.FUNCTION) {
      data.splice(0, 2);
    } else if (superMenuItem.menuType === MenuType.OPERATION) {
      data = [];
    }
  }
  return data;
}
const modelFormSetting: FormItemData<Partial<MenuItem>>[] = [
  {
    key: "menuName",
    max: 32,
    pattern: PatternKey.code,
  },
  {
    key: "menuType",
    label: "菜单类型",
    type: FormItemComponentType.SELECT,
    props: {
      options: getMenuTypeData(),
    },
  },
  {
    key: "orderNum",
    label: "显示排序",
    type: FormItemComponentType.NUMBER,
    props: {
      min: 0,
      max: 999,
    },
  },
];

const CURDModalIns = shallowRef<CURDDialogExpose>();
const showOptions = ref<ShowCURDModalOptions>();

const { pagination, tableData, tableLoading, curd, reloadTable } = useCURD<MenuItem>({
  getDataUrl: Api.getMenuTreeData,
  createUrl: Api.menu,
  updateUrl: Api.menu,
  deleteUrl: Api.menu,
  loadFilter(data) {
    handleMenuSort(data);
    return data;
  },
});

const operData: OperItem<MenuItem>[] = [
  {
    label: t("common.edit"),
    handler: showUpdateModal,
  },
];
function showCreateModal() {
  curMenu.value = undefined;
  showOptions.value = { action: CURDAction.CREATE };
}
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function handleDelete(record) {
  showOptions.value = { action: CURDAction.DELETE, record };
}
function beforeOk(e: CURDModalEvent<Partial<MenuItem>>) {
  if (e.model) {
    if (e.action === CURDAction.CREATE && e.model) {
      if (curMenu.value) {
        e.model.parentId = curMenu.value.menuId;
      }
    }
  }
}
function open(e: CURDModalEvent<Partial<MenuItem>>) {
  if (CURDModalIns.value) {
    CURDModalIns.value.toggleField("menuType", e.action === CURDAction.UPDATE);
  }
  if (e.formItemData && e.action === CURDAction.CREATE) {
    const target = e.formItemData.find((el) => el.key === "menuType");
    if (target && target.props) {
      target.props.options = getMenuTypeData(curMenu.value);
    }
  }
}

const curMenu = shallowRef<MenuItem>();
function addSubMenu(record) {
  curMenu.value = record;
  showOptions.value = { action: CURDAction.CREATE };
}
</script>
